/**
 *
 */
package org.suren.littlebird.actions.logger;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.suren.littlebird.Activator;
import org.suren.littlebird.console.LogListener;
import org.suren.littlebird.preferences.PreferenceConstants;
import org.suren.littlebird.server.LogServer;
import org.suren.littlebird.server.LogServerListener;

/**
 * @author suren
 * @since 2015-2-2
 */
public class SuRenLoggerBridgeStartAction extends Action
{
	private LogServer logServer;
	private IPreferenceStore store;
	private LogServerListener logServerListener;

	private static final String T_START = "Start";
	private static final String T_STOP = "Stop";

	private String text = T_START;

	/**
	 * @param logServer
	 */
	public SuRenLoggerBridgeStartAction(LogServer logServer)
	{
		this.logServer = logServer;
		this.store = Activator.getDefault().getPreferenceStore();
		this.logServerListener = new LogListener();

		if(logServer != null)
		{
			logServer.setListener(logServerListener);
		}
	}

	@Override
	public ImageDescriptor getImageDescriptor()
	{
		return Activator.getImageDescriptor("icons/start.gif");
	}

	@Override
	public void run()
	{
		super.run();

		if(logServer == null)
		{
			return;
		}

		String logLayout = this.store.getString(PreferenceConstants.P_LOGGER_LAYOUT);
		int port = this.store.getInt(PreferenceConstants.P_LOGGER_BRIDGE_PORT);

		logServer.setLogLayout(logLayout);

		if(!logServer.isInited())
		{
			logServer.init(port);
			new Thread(logServer, "LogServer").start();
			text = T_STOP;
		}
		else
		{
			logServer.stop();
			text = T_START;
		}

		setText(text);
		setToolTipText(text + " the Logger Bridge");
	}

}
